<template>
  <div>
    <el-form
      ref="editFormRef"
      :model="editData"
      :rules="menuFormRules"
      label-width="100px"
    >
      <el-form-item
        label="类目名称"
        prop="name"
      >
        <el-input
          v-model="editData.name"
          placeholder="请输入类目名称"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="submitMenuForm"
          :loading="loading"
        >提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script lang="ts">
import { CategoryData } from '@/api/category'
import { ElForm } from 'element-plus'
import { defineComponent, PropType, ref, watchEffect } from 'vue'
type FormInstance = InstanceType<typeof ElForm>
export default defineComponent({
  name: 'EditCategory',
  props: {
    type: {
      type: Number,
      required: true
    },
    data: {
      type: Object as PropType<CategoryData>
    }
  },
  emit: ['submit'],
  setup(props, { emit }) {
    const loading = ref(false)
    const editFormRef = ref<FormInstance | null>(null)
    const editData = ref({
      name: ''
    })
    const defaultProps = {
      name: ''
    }
    watchEffect(() => {
      if (props.data) {
        editFormRef.value?.clearValidate()
        editData.value = { ...defaultProps, ...props.data }
      }
    })
    // 验证规则
    const menuFormRules = {
      name: [{
        required: true,
        message: '请输入类目名称',
        trigger: 'blur'
      }]
    }
    // 提交
    const submitMenuForm = () => {
      (editFormRef.value as FormInstance).validate(valid => {
        if (valid) {
          emit('submit', editData.value)
        }
      })
    }
    return {
      loading,
      menuFormRules,
      editFormRef,
      editData,
      submitMenuForm
    }
  }
})
</script>
